import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockExample {

    private String data;

    private ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();

    public void readData() {
        reentrantReadWriteLock.readLock().lock();
        try {
            Thread.sleep(4000);
            System.out.println(Thread.currentThread().getName() + " ReadData data : " + data);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            reentrantReadWriteLock.readLock().unlock();
        }
    }

    public void writeData(String data) {
        reentrantReadWriteLock.writeLock().lock();
        try {
            Thread.sleep(3000);
            this.data = data;
            System.out.println(Thread.currentThread().getName() +  " WriteData data : " + data);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
    }

    public static void main(String[] args) {

        ReadWriteLockExample readWriteLockExample = new ReadWriteLockExample();
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                readWriteLockExample.readData();
            }
        }, "读线程1");
        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                readWriteLockExample.readData();
            }
        }, "读线程2");

        Thread thread3 = new Thread(() -> {
            readWriteLockExample.writeData("今天也要加油哦!~");
        }, "写线程3");

        Thread thread4 = new Thread(() -> {
            readWriteLockExample.writeData("好的, 我们一起加油!~");
        }, "写线程4");

        thread3.start();
        thread4.start();
        thread1.start();
        thread2.start();

        try {
            thread1.join();
            thread2.join();
            thread3.join();
            thread4.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
